#!/bin/bash
echo "
############################
##     Running MPS        ##
############################"
current_time=$1
start_year=`echo $current_time | cut -b1-4`
start_month=`echo $current_time | cut -b5-6`
start_day=`echo $current_time | cut -b7-8`
start_hour=`echo $current_time | cut -b9-10`
MPSdir=$2
GFSdir=$3
##----------------------------------------------

cd ${MPSdir}/run
echo 'Runing MPS in '$(pwd)

rm -f mcv_input_${start_year}${start_month}${start_day}${start_hour}0000.nc

ln -s ${MPSdir}/build/*.exe .
./gengeo.exe

#Setting the start_time in namelist
sed -ri 's/([[:blank:]]*start_year[[:blank:]]*=) (.*)/\1 '"${start_year}"'/g' ./namelist.input
sed -ri 's/([[:blank:]]*start_month[[:blank:]]*=) (.*)/\1 '"${start_month}"'/g' ./namelist.input
sed -ri 's/([[:blank:]]*start_day[[:blank:]]*=) (.*)/\1 '"${start_day}"'/g' ./namelist.input
sed -ri 's/([[:blank:]]*start_hour[[:blank:]]*=) (.*)/\1 '"${start_hour}"'/g' ./namelist.input

sed -ri 's/([[:blank:]]*end_year[[:blank:]]*=) (.*)/\1 '"${start_year}"'/g' ./namelist.input
sed -ri 's/([[:blank:]]*end_month[[:blank:]]*=) (.*)/\1 '"${start_month}"'/g' ./namelist.input
sed -ri 's/([[:blank:]]*end_day[[:blank:]]*=) (.*)/\1 '"${start_day}"'/g' ./namelist.input
sed -ri 's/([[:blank:]]*end_hour[[:blank:]]*=) (.*)/\1 '"${start_hour}"'/g' ./namelist.input

gfs_file=${GFSdir}/${start_year}/gfs.${start_year}${start_month}${start_day}${start_hour}/gfs.t${start_hour}z.pgrb2.0p50.f000
if [ -e ${gfs_file} ]
then
  ./link_grib.csh $gfs_file
  ./ungrib.exe
  ./interpmet.exe
  ./realdata.exe
else
  echo "Error: ${gfs_file} does not exist!"
  exit
fi
